<?php
/**
 * @brief 中间件
 */
class Middleware {
    /**
     * @var Middleware 中间件实例
     */
    protected static $instance;

    /**
     * 获取中间件实例
     *
     * @return Middleware
     */
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function handle($middlewares) {
        if (!$middlewares) {
            return true;
        }
        
        $yafRequest = Yaf_Registry::get('Yaf_Request');
        $actionName = $yafRequest->action;

        foreach ($middlewares as $middleware => $setting) {
            $arr = explode(":", $setting);
            if (!$arr[1]) {
                $isCheck = true;
            } else {
                $actions = explode(',', $arr[1]);
                if (($arr[0] == '+' && in_array($actionName, $actions)) || ($arr[0] == '-' && !in_array($actionName, $actions))) {
                    $isCheck = true;
                } else {
                    $isCheck = false;
                }
            }
            
            if ($isCheck) {
                Yaf_Loader::import(APP_PATH . '/application/middlewares/' . $middleware . '.php');
                $className = 'App\Middleware\\' . $middleware;
                $objMiddleware = new $className();
                $objMiddleware->handle();
            }
        }
        
        return true;
    }
}
